package dao

import (
	"context"
	"google.golang.org/grpc"
	"google.golang.org/grpc/status"
	"prod/api/mall"
	"prod/internal/conf"
	"prod/internal/constant"
	"prod/pkg/ecode"
	"prod/pkg/log"
	"prod/pkg/network"
	"prod/pkg/request_key"
	"strings"
	"time"
)

func newMallClient(ctx context.Context, mallAddr string) (client mall.MallClient, err error) {
	var conn *grpc.ClientConn
	conn, err = grpc.Dial(mallAddr, grpc.WithInsecure(),
		grpc.WithUnaryInterceptor(network.ClientInterceptor(
			"mall", time.Second*3, mallErrorTranslator)))
	if err != nil {
		err = ecode.AppendMessage(constant.ErrRemoteError, "商城服务地址无法建立有效连接, err=%s", err.Error())
		log.FromContext(ctx).Warnw(err.Error())
		return
	}
	client = mall.NewMallClient(conn)
	return
}

func mallErrorTranslator(err error) (errCode *ecode.ErrorCode) {
	rpcStatus := status.Convert(err)
	for _, detail := range rpcStatus.Details() {
		switch t := detail.(type) {
		case *mall.DefaultResp:
			errCode = ecode.NewError(t.ErrorCode, t.ErrorMessage, ecode.ErrorType{
				GRPCCode: rpcStatus.Code(),
				ErrType:  t.ErrorType,
			})
			return
		}
	}
	errCode = ecode.AppendMessage(
		constant.ErrRemoteError, "商城服务系统错误，请稍后再试")
	return
}

func (d *Dao) ShelfProdsOnShelfCheck(ctx context.Context, sgId uint32, ids []uint64,
	prodNameMap map[uint64]string) (err error) {
	if d.mallClient == nil {
		if d.mallClient, err = newMallClient(
			ctx, conf.Conf.Downstream.MallAddress); err != nil {
			return
		}
	}
	var resp *mall.ShelfProdsOnShelfCheckResp
	clientCtx, cancel := request_key.NewOutGoingContext(ctx, time.Second*3)
	defer cancel()
	if resp, err = d.mallClient.ShelfProdsOnShelfCheck(clientCtx, &mall.ShelfProdsOnShelfCheckRequest{
		SgId: sgId,
		Ids:  ids,
	}); err != nil {
		return
	}
	if len(resp.Ids) != 0 {
		prodNames := make([]string, 0)
		for _, prodId := range resp.Ids {
			prodNames = append(prodNames, prodNameMap[prodId])
		}
		err = ecode.AppendMessage(constant.ErrForbiddenAction, "商品%s在商城货架中，不能删除",
			strings.Join(prodNames, ","))
		return
	}
	return
}
